package com.xuecheng.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.*;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mappers.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-20
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {
        @Autowired
        private VodTemplate vodTemplate;
        @Override
        public ResponseResult createToken(VodUploadDto dto) throws Exception {
                // 获取 视频展示名 和 文件名
                String title = dto.getTitle();
                String fileName = dto.getFileName();
                if(StringUtils.isEmpty(title) || StringUtils.isEmpty(fileName)){
                        throw new BusinessException(ErrorCode.DATAERROR);
                }
                // 调用工具类方法 获取上传凭证
                CreateUploadVideoResponse response = vodTemplate.createUploadVideo(title, fileName);
                // 构造返回值
                VodUploadVo vo = new VodUploadVo();
                vo.setRequestId(response.getRequestId());
                vo.setUploadAddress(response.getUploadAddress());
                vo.setUploadAuth(response.getUploadAuth());
                vo.setVideoId(response.getVideoId());
                vo.setUserId(AuthInfoHolder.getUserId().toString());
                return ResponseResult.okResult(vo);
        }

        @Override
        public ResponseResult refreshToken(String videoId) throws Exception {
                // 获取刷新凭证的响应
                RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);
                // 构建返回值
                VodUploadVo vo = new VodUploadVo();
                vo.setRequestId(response.getRequestId());
                vo.setUploadAddress(response.getUploadAddress());
                vo.setUploadAuth(response.getUploadAuth());
                vo.setVideoId(response.getVideoId());
                vo.setUserId(AuthInfoHolder.getUserId().toString());
                return ResponseResult.okResult(vo);
        }

        @Override
        public ResponseResult saveMedia(MediaDto dto) throws Exception {
                // 构建实体媒资对象
                Media media = BeanHelper.copyProperties(dto, Media.class);
                // 设置基本参数
                media.setCompanyName(AuthInfoHolder.getAuthInfo().getCompanyName());
                media.setCreateDate(new Date());
                media.setStatus(CommonConstants.USING_FLAG.toString());
                media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS);
                // 设置 阿里云 相关参数，查询阿里云中视频的详情
                GetPlayInfoResponse response = vodTemplate.getPlayInfo(dto.getFileId());
                List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
                GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);
                String duration = playInfo.getDuration();  // 视频播时长
                String playURL = playInfo.getPlayURL();  // 视频地址
                media.setTimelength(duration);
                media.setUrl(playURL);
                // 保存
                boolean save = this.save(media);
                if(!save){
                        throw new BusinessException(ErrorCode.ERROR);
                }
                // 返回
                return ResponseResult.okResult();
        }

        @Override
        public ResponseResult findMediaList(PageRequest pageRequest, MediaQueryDto dto) {
                // 构造分页对象
                Page<Media> page = new Page<>(pageRequest.getPageNo(),pageRequest.getPageSize());
                // 设置查询条件
                LambdaQueryWrapper<Media> queryWrapper = new LambdaQueryWrapper<>();
                if (!StringUtils.isEmpty(dto.getAuditStatus())) {
                        queryWrapper.eq(Media::getAuditStatus,dto.getAuditStatus());
                }
                if (!StringUtils.isEmpty(dto.getFilename())) {
                        queryWrapper.like(Media::getFilename,dto.getFilename());
                }
                if (!StringUtils.isEmpty(dto.getType())) {
                        queryWrapper.eq(Media::getType,dto.getType());
                }
                // 分页查询
                IPage<Media> mediaPage = this.page(page, queryWrapper);
                // 构建返回值
                List<Media> mediaList = mediaPage.getRecords();
                String jsonString = JSON.toJSONString(mediaList);
                List<MediaVo> vos = JSONObject.parseArray(jsonString, MediaVo.class);
                return PageResponseResult.okResult(mediaPage.getTotal(),vos); // 总条数 数据列表
        }

        @Override
        public ResponseResult deleteById(Long mediaId) {
                // 判断媒体资料的状态
                Media media = this.getById(mediaId);
                boolean remove = this.removeById(media);
                if(!remove){
                        throw new BusinessException(ErrorCode.DELETEERROR);
                }
                return ResponseResult.okResult(remove);
        }

        @Override
        public ResponseResult audit(MediaAuditDto dto) {
                if(dto == null){
                        throw new BusinessException(ErrorCode.PARAMSERROR);
                }
                // 媒资状态判断
                Media media = this.getById(dto.getId());
                if(MediaConstants.AUDIT_PASTED_STATUS.equals(media.getAuditStatus())){
                        throw new BusinessException(ErrorCode.MEDIABINDERROR);
                }
                media.setAuditStatus(dto.getAuditStatus());
                media.setAuditMind(dto.getAuditMind());
                boolean update = this.updateById(media);
                if(!update){
                        throw new BusinessException(ErrorCode.UPDATEEERROR);
                }
                return ResponseResult.okResult(null);
        }

        @Override
        public ResponseResult findMediaUrl(Long mediaId) throws Exception {
                // 根据id查询媒资对象
                Media media = this.getById(mediaId);
                // 获取媒资在阿里云的id
                String id = media.getFileId();
                // 调用工具获取播放信息
                GetPlayInfoResponse playInfo = vodTemplate.getPlayInfo(id);
                // 提取播放地址
                GetPlayInfoResponse.PlayInfo info = playInfo.getPlayInfoList().get(0);
                String playURL = info.getPlayURL();
                // 返回
                ResourceVo resourceVo = new ResourceVo();
                resourceVo.setPlayUrl(playURL);
                return ResponseResult.okResult(resourceVo);
        }
}
